<?php

namespace app\partners\controller;

use app\admin\model\AdminUser;
use app\model\AdminAgent;
use app\model\AdminAgent as AdminAgentModel;
use app\common\controller\Adminbase;
use think\Db;
use think\facade\Cookie;
use think\facade\Validate;
use util\Logger;

class Agent extends Adminbase
{

    public function index()
    {
        $model = 'AdminAgent';

        if ($this->request->isAjax()) {
            $map = $this->buildParamsMap();

            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $query = AdminAgent::where($map)
                ->field('agent.*, admin.username, admin.password')
                ->alias('agent')
                ->leftJoin('admin', 'admin.id = agent.admin_id')
                ->where('admin.roleid', 'eq', 2);

            $list   = $query
                ->withAttr('image', function ($value) {
                    return $value ? get_file_path($value, 1) : '';
                })
                ->withAttr('total_money', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : '';
                })
                ->withAttr('money', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : '';
                })
                ->page($page, $pageSize)
                ->select();
            $total  = $query->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setDataUrl()
            ->setFormUrl('form')
            ->setSwitchTpl('switchTpl', 'status')
            ->setSwitchTpl('imageTpl', 'image')
            ->setDelAllBtn(false)
            ->setDelUrl('delete')
            ->setModel($model)
            ->setLimit()
            ->addTableCheckBox()
            ->addTableColumn('id', 'ID', 80, null, true)
            ->addTableColumn('name', '团长名称')
            ->addTableColumn('username', '用户名')
            ->addTableColumn('mobile', '手机号码')
            ->addTableColumn('level_count', '升级推客次数')
            ->addTableColumn('remark', '标签')
//            ->addTableColumn('total_money', '总收益（元）')
//            ->addTableColumn('money', '余额（元）')
            ->addTableOperation()
            ->returnForm();

        $url = request()->domain() . '/agent.php/admin/index/login';
        $this->assign('text', "团长后台链接：<a href='{$url}' target='_blank'>$url</a>");
        return $this->fetch('admin@common/lists');
    }

    public function form()
    {
        $model = 'AdminAgent';

        $id = $this->request->param('id/d');
        if (isset($id) && $id > 0) {
            $password_tip = '6-20位字符，可由英文、数字及标点符号组成，不修改不填写';
            $info         = AdminAgent::field('agent.*, admin.username')
                ->alias('agent')
                ->leftJoin('admin', 'admin.id = agent.admin_id')->where('agent.id', 'eq', $id)->find();
            $this->assign('id', $id);
            $this->assign('action', 2);
        } else {
            $password_tip = '6-20位字符，可由英文、数字及标点符号组成';
            $this->assign('action', 1);
            $info = [
                'rules'       => [1, 2],
                'level_count' => 0,
            ];
        }
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $rule = [
                'name|团长名称' => 'require|max:30',
                'remark|标签'     => 'max:100',
                'mobile|手机号码' => 'mobile',
            ];
            if ($data['action'] == 1) {
                $rule['username|用户名'] = 'unique:admin|require|alphaDash|length:4,20';
                $rule['password|密码']   = 'require|alphaDash|length:6,20';
            } else {
                $rule['username|用户名'] = 'require|alphaDash|length:4,20';
            }
            $validate = Validate::make($rule);
            if (!$validate->check($data)) {
                return json(['code' => -1, 'msg' => $validate->getError()]);
            }
            $password = $encrypt = '';
            if (!empty($data['password'])) {
                $passwordinfo = encrypt_password($data['password']);
                $password     = $passwordinfo['password'];
                $encrypt      = $passwordinfo['encrypt'];
            }
            if (empty($data['rules'])) {
                $data['rules'] = '';
            }

            Db::startTrans();
            try {
                if ($data['action'] == 1) {
                    $admin_res        = AdminUser::create([
                        'username' => $data['username'],
                        'password' => $password,
                        'encrypt'  => $encrypt,
                        'nickname' => $data['name'],
                        'roleid'   => 2,
                    ]);
                    $data['admin_id'] = $admin_res->id;
                    $uuid             = generateUniqueString();
                    $data['uuid']     = $uuid;
                    $res              = saveDataByModel(AdminAgentModel::class, $data);
                } else {
                    $admin_id   = $info['admin_id'];
                    $admin_save = [
                        'username' => $data['username'],
                        'nickname' => $data['name'],
                    ];
                    if ($password) {
                        $admin_save['password'] = $password;
                        $admin_save['encrypt']  = $encrypt;
                    }
                    $admin_res = AdminUser::where('id', $admin_id)->update($admin_save);
                    $res       = saveDataByModel(AdminAgentModel::class, $data, ['id' => $data['id']]);
                }
                if ($res !== false && $admin_res !== false) {
                    Db::commit();
                    return json(['code' => 0, 'msg' => '操作成功']);
                } else {
                    Db::rollback();
                    return json(['code' => -1, 'msg' => '操作失败']);
                }
            } catch (\Exception $e) {
                $log = [
                    'file'    => $e->getFile(),
                    'line'    => $e->getLine(),
                    'message' => $e->getMessage(),
                ];
                Logger::error('添加失败', $log);
                Db::rollback();
                return json(['code' => -1, 'msg' => '操作失败']);
            }

        }

        $builder = new \app\common\controller\FormBuilder();
        $builder
            ->setUrl('form')
            ->setModel($model)
            ->setSuccessUrl()
            ->addFormItem('name', 'text', '团长名称', '', [], 1)
            ->addFormItem('username', 'text', '用户名', '4-20位字符，由字母和数字组成', [], 1)
            ->addFormItem('password', 'text', '密码', $password_tip)
            ->addFormItem('mobile', 'text', '手机号码')
            ->addFormItem('level_count', 'gtnumber', '升级推客次数')
            ->addFormItem('rules', 'checkbox', '权限组', '', AdminAgent::RULE_ARRAY)
            ->addFormItem('tip', 'tip', '', "店铺邀请：团长可以将小店绑定至团长后台，绑定后该小店的商品会归属于该团长，商品被推广后团长会获得佣金")
            ->addFormItem('tip', 'tip', '', "佣金设置：开启后，团长推客的佣金比例由团长自定义设置；不开启则统一按照本后台的佣金比例进行分销")
            ->addFormItem('remark', 'text', '标签')
            ->setFormData($info)
            ->returnForm();
        $this->assign('is_verify', 0);
        return $this->fetch('admin@common/form');
    }

    public function delete()
    {
        $id   = $this->request->param('id/d');
        $info = AdminAgent::field('admin_id')->where('id', $id)->find();
        if (empty($info)) {
            return json(['code' => -1, 'msg' => '用户不存在']);
        }
        Db::startTrans();
        try {
            $res       = AdminAgent::where('id', $id)->delete();
            $admin_res = AdminUser::where('id', $info['admin_id'])->delete();
            if ($res !== false && $admin_res !== false) {
                Db::commit();
                return json(['code' => 0, 'msg' => '操作成功']);
            } else {
                Db::rollback();
                return json(['code' => -1, 'msg' => '操作失败']);
            }
        } catch (\Exception $e) {
            $log = [
                'file'    => $e->getFile(),
                'line'    => $e->getLine(),
                'message' => $e->getMessage(),
            ];
            Logger::error('删除失败', $log);
            Db::rollback();
            return json(['code' => -1, 'msg' => '操作失败']);
        }
    }

}
